﻿using System;
using System.Data;
using System.Collections;
using System.Web.UI.WebControls;
using Framework.Library;
using Framework.Library.Components.Security;
using Framework.Library.Components.Users;
using Framework.Library.Utilities;
using Framework.Library.Components.Commands;
using System.Collections.Generic;

namespace Portal.Administrator.Users
{
	public partial class UserManagement : AuthenticatedControl
	{
        protected void Page_Load(object sender, EventArgs e)
		{
            if ((!CurrentUser.IsSuperAdmin && CommandController.IsSystemModule(AppEnv.CommandID())) || !CommandController.IsAvailableForUser(AppEnv.CommandID(), CurrentUser.UserID, Convert.ToInt32(AppEnv.PortalId())))
                Response.Redirect(AppEnv.ADMIN_CMD, true);
			if (!Page.IsPostBack)
			{
                ArrayList arrLetters = new ArrayList();
				for (char c = 'A'; c <= 'Z'; c++)
				{
					arrLetters.Add(c.ToString());
				}
				arrLetters.Add("All");
				rptLetters.DataSource = arrLetters;
				rptLetters.ItemDataBound += new RepeaterItemEventHandler(rptLetters_ItemDataBound);
				rptLetters.DataBind();
                lblCommandName.Text = AppEnv.CommandName();
			}
		}
        private void rptLetters_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                LinkButton lnkLetter = (LinkButton)e.Item.FindControl("lnkLetter");
                lnkLetter.Text = e.Item.DataItem.ToString();
                lnkLetter.CommandArgument = e.Item.DataItem.ToString();
            }
        }
        public void rptLetters_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "Alpha")
            {
                if (ConvertUtility.ToString(e.CommandArgument) != "All")
                {
                    LoadUser("", "", e.CommandArgument.ToString(), CurrentUser.UserID, ConvertUtility.ToInt32(AppEnv.PortalId()));
                }
                else
                {
                    LoadUser("", "", "", CurrentUser.UserID, ConvertUtility.ToInt32(AppEnv.PortalId()));
                }
            }
        }
        protected void dtgUsers_ItemDataBound(object sender, RepeaterItemEventArgs e)
		{
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
			{
                ImageButton btnImgDeleteUser = (ImageButton)e.Item.FindControl("btnImgDeleteUser");                
                HiddenField lblKey = (HiddenField)e.Item.FindControl("lblKey");
                Label lblUsername = (Label)e.Item.FindControl("lblUsername");
                Label lblEmail = (Label)e.Item.FindControl("lblEmail");
                CheckBox DeleteThis = (CheckBox)e.Item.FindControl("DeleteThis");
			    
                btnImgDeleteUser.OnClientClick = MiscUtility.MSG_DELETE_CONFIRM;    
          
				DataRowView curData = (DataRowView)e.Item.DataItem;
                UserInfo userinfo = UserController.GetUser(Convert.ToInt32(lblKey.Value));

                if (userinfo.IsSuperAdmin || (lblEmail.Text == AppEnv.ADMIN_EMAIL) || (lblUsername.Text == CurrentUser.Username))
                {
                    if (lblEmail.Text == AppEnv.ADMIN_EMAIL)
                    {
                        e.Item.Visible = false;
                    }
                    else
                    {
                        e.Item.Visible = true;
                    }
                    btnImgDeleteUser.Visible = false;
                    DeleteThis.Visible = false;
                }
			}
		}
        protected void dtgUsers_ItemCommand(object sender, RepeaterCommandEventArgs e)
		{
			int userId = ConvertUtility.ToInt32(e.CommandArgument);
			switch (e.CommandName)
			{
				case "manageprofile":
					Response.Redirect(AppEnv.AdminUrlParams(CommandController.GetCommandbyID((int)PortalControls.UserCreate)) + "&uid=" + userId);
					break;
				case "managepassword":
                    Response.Redirect(AppEnv.AdminUrlParams(CommandController.GetCommandbyID((int)PortalControls.UserPassword)) + "&uid=" + userId);
					break;				
				case "deleteuser":
					try
					{
						UserController.DeleteUser(userId);
						this.lblUpdateStatus.Text = MiscUtility.MSG_UPDATE_SUCCESS;
                        LoadUser("", "", "", CurrentUser.UserID, ConvertUtility.ToInt32(AppEnv.PortalId()));
					}
					catch (Exception ex)
					{
						this.lblUpdateStatus.Text = ex.Message;
					}
					break;
				default:
					break;
			}
		}
		protected void btnAddUser_Click(object sender, EventArgs e)
		{
            Response.Redirect(AppEnv.AdminUrlParams(CommandController.GetCommandbyID((int)PortalControls.UserCreate)));
		}
		private void LoadUser(string keyword, string searchby, string filter, int userid, int portalid)
		{			
            DataTable dtUsers = UserController.GetUsers(keyword, searchby, filter, portalid);
            dtgUsers.DataSource = dtUsers;
            dtgUsers.ItemDataBound +=new RepeaterItemEventHandler(dtgUsers_ItemDataBound);
			dtgUsers.DataBind();
		}
        protected void btnDeleteSelected_Click(object sender, EventArgs e)
        {
            List<RepeaterItem> removed = new List<RepeaterItem>();
            foreach(RepeaterItem items in dtgUsers.Items)
            {
                removed.Add(items);
            }
            foreach(RepeaterItem it in removed)
            {
                CheckBox deleteChkBxItem = (CheckBox)it.FindControl("DeleteThis");
                if (deleteChkBxItem.Checked)
                {
                    string strTemp = ((HiddenField)it.FindControl("lblKey")).Value;
                    UserController.DeleteUser(Convert.ToInt32(strTemp.ToString()));
                    LoadUser("", "", "", CurrentUser.UserID, ConvertUtility.ToInt32(AppEnv.PortalId()));
                }
            }                       
        }
       
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            LoadUser(txtKeyword.Text, dropSearchBy.SelectedValue, "", CurrentUser.UserID, ConvertUtility.ToInt32(AppEnv.PortalId()));
        }

        protected void btnPermission_Click(object sender, EventArgs e)
        {
            Response.Redirect(AppEnv.AdminUrlParams(CommandController.GetCommandbyID((int)PortalControls.UserPermision)));
        }
	}
}